#include "wgWindow.h"


void wgRenderCallback();
void wgReshapeCallback(int width, int height);
void wgKeyboardCallback(unsigned char, int, int);
void wgKeyboardSpecialCallback(int, int, int);

void wgIddleCallback();




void wgWindow::CreateAppWindow(int width, int height, const char * caption)
{
	


	if(!SDL_WasInit(SDL_INIT_VIDEO))
		SDL_Init(SDL_INIT_VIDEO);


	  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
      SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1 );

	SDL_Surface* screen = SDL_SetVideoMode( width, height, 32, SDL_OPENGL);
	windowWidth = screen->w;
	windowHeight = screen->h;
	if(screen == 0)
	{
		cout << SDL_GetError() << endl;
		return;
	}

	Reshape(windowWidth, windowHeight);

	 //SDL_WM_GrabInput(SDL_GRAB_ON);



	windowID = GetActiveWindow();
	wgResourceManager::RegisterWindow(this);



}

wgWindow::~wgWindow()
{
	/*if(windowID > 0)
		glutDestroyWindow(windowID);*/
}

void wgWindow::Reshape(int w, int h)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glViewport(0, 0, w, h);


	//gluOrtho2D(0, w, h, 0);


	gluPerspective(45, (float)w / h, 1, 10000);

	glMatrixMode(GL_MODELVIEW);

}



void wgRenderCallback()
{
	WINDOWID currentWindow = GetActiveWindow();
	wgWindow* window;
	if(wgResourceManager::FindWindowById(currentWindow, &window))
		window->Render();
}


void wgReshapeCallback(int width, int height)
{
	WINDOWID currentWindow = GetActiveWindow();
	wgWindow* window;
	if(wgResourceManager::FindWindowById(currentWindow, &window))
		window->Reshape(width, height);
}


void wgKeyboardCallback(unsigned char key, int mx, int my)
{
	WINDOWID currentWindow = GetActiveWindow();
	wgWindow* window;
	if(wgResourceManager::FindWindowById(currentWindow, &window))
		window->HandleKeyboard(key, mx, my);
}


void wgKeyboardSpecialCallback(int key, int mx, int my)
{
	WINDOWID currentWindow = GetActiveWindow();
	wgWindow* window;
	if(wgResourceManager::FindWindowById(currentWindow, &window))
		window->HandleKeyboardSpecial(key, mx, my);
}

void wgIddleCallback()
{
	//glutPostRedisplay();
}


void wgWindow::StartMainLoop()
{

	SDL_Event evt;

    while(1)
    {
        while(SDL_PollEvent(&evt))
        {
            switch(evt.type)
            {
                case SDL_QUIT:
                {
					return;
                }
				case SDL_KEYDOWN:
					switch(evt.key.keysym.sym)
					{
					case SDLK_F12:
						SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
						break;
					case SDLK_ESCAPE:
						return;
					}
				
                    
            }
			
		}
		
        wgRenderCallback();
		
    }

}